package com.whz.gateway.configure;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Mono;
import com.whz.gateway.limit.GatewayRemoteIpResolver;

import java.util.Objects;

/**
 * 限流配置
 * @author whz
 */
@Configuration
public class RateLimiterResolverConfigure {

    @Bean("remoteAddressKeyResolver")
    @ConditionalOnProperty(name = "gateway.redis.rate.limit.name",havingValue = "remoteAddressKeyResolver",matchIfMissing = false)
    public KeyResolver remoteAddressKeyResolver() {
        return exchange -> Mono.just(Objects.requireNonNull(exchange.getRequest().getRemoteAddress()).getAddress().getHostAddress());
    }

    @Bean("userKeyResolver")
    @ConditionalOnProperty(name = "gateway.redis.rate.limit.name",havingValue = "userKeyResolver",matchIfMissing = false)
    public KeyResolver userKeyResolver() {
        return exchange -> Mono.just(Objects.requireNonNull(exchange.getRequest().getQueryParams().getFirst("userId")));
    }

    @Bean("apiKeyResolver")
    @ConditionalOnProperty(name = "gateway.redis.rate.limit.name",havingValue = "apiKeyResolver",matchIfMissing = false)
    public KeyResolver apiKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getPath().pathWithinApplication().value());
    }

    @Bean(GatewayRemoteIpResolver.BEAN_NAME)
    public GatewayRemoteIpResolver tongyuRemoteIpResolver() {
        return new GatewayRemoteIpResolver();
    }
}